#include "bsp_xpt2046.h"
#include "stm32f1xx_hal.h"

//******xpt2046 notes *******
/*
Control Bits in the Control Byte
(MSB) 														(LSB)
Bit 7 	Bit 6 	Bit 5 	Bit 4 	Bit 3 	Bit 2 		Bit 1 	Bit 0
	S 	A2 		A1 		A0 		MODE 	SER/DFR 	PD1 	PD0
Bit 0 y 1 ----	(PD1 - PD0) select the power- down mode
	class XPT2046(object):
	
	StartBit = 0b10000000 
	
	class ChannelSelect(object):
		X_POSITION 		= 0b01010000
		Y_POSITION 		= 0b00010000
		Z1_POSITION 	= 0b00110000
		Z2_POSITION 	= 0b01000000
		TEMPERATURE_0 	= 0b00000000
		TEMPERATURE_1 	= 0b01110000
		BATTERY_VOLTAGE = 0b00100000
		AUXILIARY 		= 0b01100000
	class ConversionSelect(object):
		_8_BIT  		= 0b00001000				//bit mode define la conversion de 8 o 12 bits
		_12_BIT 		= 0b00000000
		
		
				//0xB0 = 0b10110000    //leemos Z1 ???  ok***
				//0xD0 = 0b11010000    //leemos x ???  ok
				//0x90 = 0b10010000    //leemos y ???  ok
				//si ponemos el bit 0 y 1 a 0 	Power-down between conversions. When each
											conversion is finished, the converter enters a low
											power mode. At the start of the next conversion,
											the device instantly powers up to full power.
				//si ponemos el bit 3 a 0 estamos leyendo 12 bits
*/
//******xpt2046 notes *******


#define SPI_CS_0 HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_RESET);
#define SPI_CS_1 HAL_GPIO_WritePin(GPIOA, GPIO_PIN_4, GPIO_PIN_SET);
#define BUSY_PIN HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_1)

#define MAX_UINT32 0xffffffff

extern SPI_HandleTypeDef hspi1;


static void xpt2046_send_rev_data(uint8_t * pSend, uint8_t sendLen, uint8_t * pRev, uint8_t revLen)
{
    uint32_t timeout;
    
    SPI_CS_0;
    HAL_SPI_Transmit(&hspi1, pSend, sendLen, 500);
    
    // Check BUSY pin
    //do
    {
        timeout++;
    }
    //while(BUSY_PIN == GPIO_PIN_SET && timeout < MAX_UINT32);
    
    HAL_SPI_Receive(&hspi1, pRev, revLen, 500);
    
    SPI_CS_1;
}


uint16_t xpt2046_read_x(void)
{
    uint8_t cmd = 0xD0;
    //uint16_t result = 0;
    uint8_t result[2];
    
    xpt2046_send_rev_data(&cmd, 1, (uint8_t *)&result, 2);
    
    //return result >> 3;
    return ((result[0] & 0x7F) << 5) | (result[1] >> 3);
}

uint16_t xpt2046_read_y(void)
{
    uint8_t cmd = 0x90;
    //uint16_t result = 0;
    uint8_t result[2];
    xpt2046_send_rev_data(&cmd, 1, (uint8_t *)&result, 2);
    
    //return result >> 3;
    return ((result[0] & 0x7F) << 5) | (result[1] >> 3);
}


